from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from info import constants
from info import db
from info.models import News, Comment, CommentLike, User
from info.modules.news import news_bp
from info.utits.common import user_login_data
from info.utits.response_code import RET


@news_bp.route('/followed_user',methods=["POST"])
@user_login_data
def followed_user():
    param_dict = request.json
    user_id = param_dict.get("user_id")
    action = param_dict.get("action")
    user = g.user

    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")

    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.PARAMERR,errmsg="action参数错误")

    try:
        author = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询作者异常")
    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    if action == "follow":
        if author in user.follwed:
            return jsonify(errno=RET.DATAEXIST,errmsg="不能重复关注")
        else:
            user.followed.append(author)

    else:
        if author in user.followed:
            user.followed.remove(author)

    return jsonify(errno=RET.OK,errmsg="OK")



@news_bp.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    """评论的点赞、取消点赞接口"""
    """
    1.获取参数
        1.1 comment_id:评论id， action:点赞、取消点赞的行为（add,remove）
    2.校验参数
        2.1 非空判断
        2.2 action in ['add', 'remove']
    3.逻辑处理
        3.0 根据comment_id查询该评论
        3.1 action==add表示点赞：查询commentlike模型对象，如果不存在，再创建commentlike
        3.2 action==remove表示取消点赞：查询commentlike模型对象，如果存在，再删除这种点赞关系
    4.返回值
    """
    #1.1 用户对象 新闻id comment_id评论的id，action:(点赞、取消点赞)
    params_dict = request.json
    comment_id = params_dict.get("comment_id")
    action = params_dict.get("action")
    print(comment_id,action)
    user = g.user

    #2.1 非空判断
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    #2.2 用户是否登录判断
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    #2.3 action in ["add", "remove"]
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="action参数错误")

    # 3.0 根据comment_id查询该评论
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询评论对象异常")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    # 当前用户登录成功
    if user:
        # 3.1 action==add表示点赞：查询commentlike模型对象，如果不存在，再创建commentlike
        if action == "add":
            # 点赞
            try:
                commentlike = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == user.id).first()
                print(commentlike)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="查询点赞评论模型异常")
            # 当前用户没有对当前评论点过赞
            if not commentlike:
                # 创建CommentLike模型对象给其属性赋值
                commentlike_obj = CommentLike()
                commentlike_obj.user_id = user.id
                commentlike_obj.comment_id = comment_id

                # 添加到数据库
                db.session.add(commentlike_obj)
                # 评论的总点赞数量进行累加
                comment.like_count += 1
                print("点赞",comment.like_count)
        # 3.2 action==remove表示取消点赞：查询commentlike模型对象，如果存在，再删除这种点赞关系
        else:
            # 取消点赞
            try:
                commentlike = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == user.id).first()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="查询点赞评论模型异常")
            # 当前用户对当前评论点过赞的情况才能取消点赞
            if commentlike:
                # 从数据库删除第三张表维护的关系，即表示：取消点赞
                db.session.delete(commentlike)
                # 评论的总点赞数量进行减一
                comment.like_count -= 1
                print("取消点赞",comment.like_count)

    # 将点赞、取消点赞的修改提交回数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        # 回滚
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论点赞模型对象异常")

    #4.返回值
    return jsonify(errno=RET.OK, errmsg="OK")


@news_bp.route('/news_comment', methods=["POST"])
@user_login_data
def news_comment():
    """发布评论接口"""
    param_dict = request.json
    comment_str = param_dict.get("comment")
    news_id = param_dict.get("news_id")
    parent_id = param_dict.get("parent_id")

    user = g.user

    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    comment_obj = Comment()
    comment_obj.user_id = user.id
    comment_obj.news_id = news_id
    comment_obj.content = comment_str

    if parent_id:
        comment_obj.parent_id = parent_id

    try:
        db.session.add(comment_obj)
        db.session.commit()
    except Exception as e:
        current_app.looger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论对象异常")

    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment_obj.to_dict())


@news_bp.route('/news_collect', methods=["POST"])
@user_login_data
def news_collect():
    """用户点击收藏，取消收藏后端接口实现"""

    user = g.user
    param_dict = request.json
    news_id = param_dict.get("news_id")
    action = param_dict.get("action")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if not all([action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数内容错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻数据异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有该新闻数据")

    if action == "collect":
        user.collection_news.append(news)

    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存新闻数据到收藏列表异常")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_bp.route("/<int:news_id>", methods=["GET","POST"])
@user_login_data
def get_detail_news(news_id):
    """展示新闻详情页面"""
    # 获取当前登录的用户
    print(news_id)
    user = g.user
    try:
        # 查询点击排行侧的新闻列表，并按点击量排序显示点击量最多的n条新闻
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        # 记录错误
        current_app.logger.error(e)
        # 向前段返回json数据
        return jsonify(errno=RET.DBERR, errmsg="查询点击排行数据异常")
    # 新闻字典列表
    news_rank_dict_list = []
    for news_obj in news_rank_list if news_rank_list else []:
        news_dict = news_obj.to_dict()
        news_rank_dict_list.append(news_dict)

    try:
        # 显示在新闻列表侧的新闻
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻详情异常")

    news_dict = news.to_dict()

    is_collected = False
    # 如果用户已登录
    if user:
        if news in user.collection_news:
            is_collected = True
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询评论异常")
    # 查询每条评论的点赞 的 user_id
    # 评论id
    comment_ids = [comment.id for comment in comments]
    # 应该亮起来的赞
    likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                     CommentLike.user_id==user.id)
    like_comment_ids = [like.comment_id for like in likes]
    comment_dict_list = []
    for comment in comments if comments else []:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False

        if comment.id in like_comment_ids:
            comment_dict['is_like'] = True
        comment_dict_list.append(comment_dict)


    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_rank_dict_list,
        "news": news_dict,
        "is_collected": is_collected,
        "comments": comment_dict_list,
    }
    print(data)
    return render_template('news/detail.html', data=data)
